#!/usr/local/bin/python
# -*- coding: utf-8 -*-

import datetime
from flask import Flask, url_for, request, session, render_template, redirect
from flaskext.sqlalchemy import SQLAlchemy

from json import dumps

from bompy import app
from utils import q, table, login_required, get2parameters, formtable, textinput, unitoptions, designoptions, typeoptions, writeBarCode
from model import Refer, Header_Refer, Despatch, Stock_Despatch, Design, Stock

db = SQLAlchemy(app)

Usercode=1
@app.route('/refer')
@login_required
def refer():
    form = (
    ("Refer", textinput("RF")),
    ("Product", textinput("BC1")),
    ("Product", textinput("BC2")),
    ("Product", textinput("BC3")),
    ("Product", textinput("BC4")),
    ("Product", textinput("BC5"))

    )
    f=formtable(form,action="_refer_db")
    return render_template("refer.html",f=f)


@app.route('/_refer_db')
@get2parameters
def refer_db(RF,BC1,BC2,BC3,BC4,BC5):
    h = Header_Refer()
    h.Branch_Destination=0
    h.CAI=0
    h.Code_Destination=0
    h.Date_Create=0
    h.Date_Delivery=0
    h.Date_Exit=0
    h.Date_Order=0
    h.Date_Reception=0
    h.Date_Update=0
    h.Date_Waste=0
    h.Destination_Address="0"
    h.Destination_Bult=0
    h.Destination_Location="0"
    h.Destination_Name="0"
    h.Kilos=0
    h.Location_Create="0"
    h.Location_Update="0"
    h.Location_Waste="0"
    h.Postal_Code=0
    h.Reason_Delay="0"
    h.Refer_Branch=0
    h.Refer_Date=0
    h.Refer_Letter="0"
    h.Refer_Number=0
    h.User_Create=0
    h.User_Update=0
    h.User_Waste=0
    db.session.add(h)
    db.session.commit()
    d=Despatch()
    d.ID_Refer = h.ID_Refer
    d.ID_State = 1
    d.User_Create = Usercode
    d.Start_Date = datetime.datetime.today()
    d.End_Date = 0
    d.User_Update = 0
    db.session.add(d)
    db.session.commit()
    for i in [BC1,BC2,BC3,BC4,BC5]:
        print i
        if len(i)==12:
            print i
            s1 = i[:4]
            s2 = i[4:11]
            s3 = i[11]
            if str(writeBarCode(s1,s2)) == str(s3):
                sd = Stock_Despatch()
                for i in Design.query.all():
                    if i.isCurrent():
                        if i.ID_Design[-4:]==s1:
                            des = i
                print des.Description_Std
                sd.ID_Stock = Stock.query.filter_by(ID_Design=des.ID_Design)
                sd.ID_Despatch = d.ID_Despatch
                sd.ID_State = 1
                db.session.add(sd)
                db.session.commit()
            else:
                print "unvalid code"
        
    return redirect(url_for('start_screen'))
